﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Revolio;

namespace RevolioReader
{
    public partial class AddBookForm : Form
    {
        public AddBookForm()
        {
            InitializeComponent();
        }

        public Book Book { get; private set; }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            // Find the first numeric part in the url, and use that as the
            // book id.
            string s = txtBookID.Text;
            Match m = new Regex(@"\d+").Match(s);
            if (m.Captures.Count == 0)
            {
                MessageBox.Show(this, "Please input a valid book ID or URL.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                return;
            }
            int id = Int32.Parse(m.Captures[0].Value);

            // Load the book async.
            txtBookID.Enabled = false;
            btnOK.Visible = false;
            this.Cursor = Cursors.WaitCursor;
            Book book = await Task<Book>.Factory.StartNew(() => Book.Load(id));
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //this.Close();
        }

        private void AddBookForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show(e.CloseReason.ToString());
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int id = (int)e.Argument;
            this.Book = Book.Load(id);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
    }
}
